--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[

    蝶引来生

]]--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---
    local HEALTH_COST_PERCENT = 0.14                    -- 消耗血量百分比
    local SPELL_START_AOE_RADIUS = 2                    -- 技能开始的AOE半径
    local HIT_TARGET_SANITY_HEAL_PERCENT = 0.07         -- 击中目标时恢复精神百分比
    local DEBUFF_REMAIN_TIME = 49                       -- 蝶引来生持续时间
    local SPELL_BLAZING_BUTTERFLY_AOE_RADIOUS = 7       -- 焚身蝶火 AOE半径
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 目标扫描TAGS
    local BOUNCE_MUST_TAGS = { "_combat" }
    local BOUNCE_NO_TAGS = { "INLIMBO", "wall", "notarget", "player", "companion", "flight", "invisible", "noattack", "hiding" } -- "player", "companion", "flight", "invisible", "noattack", "hiding"
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 技能消耗
    local function health_dodelta(inst,value,...)
        if inst.components.hutao_com_healing_grove then
            inst.components.hutao_com_healing_grove:HealthDoDelta(value,...)
        else
            inst.components.health:DoDelta(value,...)
        end
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 技能状态
    local function IsTalentUnlocked(inst)
        return inst.replica.hutao_com_talent_tree:IsUnlocked("time_of_butterfly_concealment")
    end
    local function CanCastSpell(inst)
        if inst:HasTag("playerghost") then
            return false
        end
        return inst.replica.health:GetPercent() >= HEALTH_COST_PERCENT
    end
    local function CanStopSpell(inst)
        if inst:HasTag("playerghost") then
            return false
        end
        local health_cost = inst.replica.hutao_com_butterfly_s_embrace:GetHealthCost()
        if not IsTalentUnlocked(inst) then
            ------------------------------------------------------------------------------
            --- 天赋没解锁
                if inst.replica.health:GetCurrent() >= 0.5*health_cost then
                    return true
                else
                    return false
                end
            ------------------------------------------------------------------------------
        else
            ------------------------------------------------------------------------------
            --- 天赋解锁了
                if inst.replica.health:GetCurrent() >= 0.5*health_cost then
                    return true
                else
                    return false
                end
            ------------------------------------------------------------------------------
        end


    end
    local function IsSpellActiving(inst)
        return inst.replica.hutao_com_butterfly_s_embrace:IsActiving()
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---  【蝶隐之时】 debuff  Vanishing Butterfly Moment  vanishing_butterfly_moment    
    local function Add_Debuff_Vanishing_Butterfly_Moment(inst)
        inst:AddDebuff("hutao_debuff_vanishing_butterfly_moment","hutao_debuff_vanishing_butterfly_moment")    
    end
    local function Remove_Debuff_Vanishing_Butterfly_Moment(inst)
        inst:RemoveDebuff("hutao_debuff_vanishing_butterfly_moment")
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 技能开启。
    local function Spell_Start_Fn(inst)
        if IsSpellActiving(inst) or not CanCastSpell(inst) then
            return
        end
        local max_health = inst.components.health.maxhealth
        local health_cost = max_health * HEALTH_COST_PERCENT
        inst.components.hutao_com_butterfly_s_embrace:Start(health_cost)
        print("蝶引来生 开始")
        inst.components.hutao_com_dialogue:SayWithCD("hutao_com_butterfly_s_embrace.start",10)
    end
    local function Spell_Fn(inst)
        -----------------------------------------------------------------------
        --- 技能消耗
            local health_cost = inst.components.hutao_com_butterfly_s_embrace:GetHealthCost()
            -- inst.components.health:DoDelta(-health_cost,true)
            health_dodelta(inst,-health_cost,true)
            inst.components.hutao_com_butterfly_s_embrace:SetDebuffRemainTime(DEBUFF_REMAIN_TIME)
            Remove_Debuff_Vanishing_Butterfly_Moment(inst)
            SpawnPrefab("hutao_sfx_pink_flame"):PushEvent("Set",{target = inst})
        -----------------------------------------------------------------------
        --- 寻找范围内目标
            local x,y,z = inst.Transform:GetWorldPosition()
            local ents = TheSim:FindEntities(x,0,z,SPELL_START_AOE_RADIUS,BOUNCE_MUST_TAGS,BOUNCE_NO_TAGS)
            local targets = {}
            for _,temp_target in ipairs(ents) do
                if temp_target and temp_target:IsValid() and temp_target.components.health and not temp_target.components.health:IsDead() then
                    table.insert(targets,temp_target)
                end
            end
            -- if #targets == 0 then
            --     return
            -- end
        -----------------------------------------------------------------------
        --- 造成伤害 并 恢复 sanity
            local max_sanity = inst.components.sanity.max
            local sanity_heal = max_sanity * HIT_TARGET_SANITY_HEAL_PERCENT

            for k, temp_target in pairs(targets) do
                inst.components.hutao_com_fire_damage:DoFireDamage(temp_target,health_cost*3)
                inst.components.sanity:DoDelta(sanity_heal)
                SpawnPrefab("hutao_sfx_pink_flame"):PushEvent("Set",{target = temp_target})
            end
        -----------------------------------------------------------------------
        ---
            inst:PushEvent("hutao_event.spell_finish_for_plum_blossom",{
                pt = Vector3(x,y,z),
                radius = SPELL_START_AOE_RADIUS,
                spell = "butterfly_s_embrace",
            })
        -----------------------------------------------------------------------


    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 技能关闭
    local function Spell_Blazing_Butterfly(inst,health_cost) --- 焚身蝶火
        -----------------------------------------------------------------------
        --- 
            inst:PushEvent("hutao_event.spell_finish_for_plum_blossom",{
                pt = Vector3(inst.Transform:GetWorldPosition()),
                radius = SPELL_BLAZING_BUTTERFLY_AOE_RADIOUS,
                spell = "blazing_butterfly",
            })
        -----------------------------------------------------------------------
        --- 寻找范围内目标
            local x,y,z = inst.Transform:GetWorldPosition()
            local ents = TheSim:FindEntities(x,0,z,SPELL_BLAZING_BUTTERFLY_AOE_RADIOUS,BOUNCE_MUST_TAGS,BOUNCE_NO_TAGS)
            local targets = {}
            for _,temp_target in ipairs(ents) do
                if temp_target and temp_target:IsValid() and temp_target.components.health and not temp_target.components.health:IsDead() then
                    table.insert(targets,temp_target)
                end
            end
            if #targets == 0 then
                return
            end
        -----------------------------------------------------------------------
        -- --造成伤害
            --[[
                放出【焚身蝶火】，对身边较大范围内敌人造成本轮【彼岸蝶舞】消耗生命总量2倍（描述如此，但是图省事，实际公式为2H+6t）的引魂火伤害
                （注：计算倍率未来有可能发生变化因此最好留个接口）。
                若【焚身蝶火】命中的单位身上有【血梅香】状态，则触发一次血梅香伤害但不会重置目标身上血梅香的持续时间。
            ]]
            local damage = 2*health_cost+6*DEBUFF_REMAIN_TIME
            for k, temp_target in pairs(targets) do
                inst.components.hutao_com_fire_damage:DoFireDamage(temp_target,damage)
                SpawnPrefab("hutao_sfx_pink_flame"):PushEvent("Set",{target = temp_target})
                local has_debuff,debuff_inst = inst.components.hutao_com_blood_plum_scent_for_player:HasDebuff(temp_target)
                if has_debuff and debuff_inst then
                    debuff_inst.components.hutao_com_blood_plum_scent_for_debuff:DoDamage()
                end
            end
        -----------------------------------------------------------------------
        ---
            Add_Debuff_Vanishing_Butterfly_Moment(inst)
        -----------------------------------------------------------------------
    end
    local function Spell_Stop_Fn(inst)
        --[[
            彼岸蝶舞状态按C键关闭。关闭时，消耗相当于0.5H生命值（当前生命值不足0.5H则无法关闭），结算后清空本轮记录的H与t。
            *点出【蝶隐之时】后变为：若开启了不足7秒，则关闭时还是消耗0.5H生命值。
            若开启了至少7秒，则关闭时，消耗H生命值（大于0.5H不足H仍能关闭，会消耗血量至1点）
        ]]--
        if not IsSpellActiving(inst) then
            return
        end
        print("蝶引来生 主动关闭")

        local health_cost = inst.components.hutao_com_butterfly_s_embrace:GetHealthCost()
        if not IsTalentUnlocked(inst) then
            -- inst.components.health:DoDelta(-0.5*health_cost)
            health_dodelta(inst,-0.5*health_cost)
        else
            --- 天赋解锁了
            if inst.replica.hutao_com_butterfly_s_embrace:GetDebuffActiveTime() < 7 then
                -- inst.components.health:DoDelta(-0.5*health_cost)
                health_dodelta(inst,-0.5*health_cost)
            else
                if inst.components.health.currenthealth > health_cost then
                    -- inst.components.health:DoDelta(-health_cost)
                    health_dodelta(inst,-health_cost)
                else
                    inst.components.health.currenthealth = 1
                    inst.components.health:ForceUpdateHUD()
                end
            end
            Spell_Blazing_Butterfly(inst,health_cost)
        end
        inst.components.hutao_com_butterfly_s_embrace:Stop()
        SpawnPrefab("hutao_sfx_pink_flame"):PushEvent("Set",{target = inst})        
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--  按键
    local client_side_hokey_cd_task = nil
    local function IsClientSideHotkeyCD()
        return client_side_hokey_cd_task ~= nil
    end
    local function ClientSideHotkeyCD(inst)
        client_side_hokey_cd_task = inst:DoTaskInTime(1,function()
            client_side_hokey_cd_task = nil
        end)
    end
    local function hotkey_press(inst)
        -------------------------------------------------------------------------------------
        --- 客户端CD
            if IsClientSideHotkeyCD() then
                TheFrontEnd:GetSound():PlaySound("dontstarve/HUD/click_negative", nil, .4)
                return
            end
        -------------------------------------------------------------------------------------
        --- 技能停止
            if IsSpellActiving(inst) then
                if CanStopSpell(inst) then
                    inst.replica.hutao_com_rpc_event:PushEvent("hutao_event.spell.BUTTERFLY_S_EMBRACE.stop")
                    ClientSideHotkeyCD(inst)
                else
                    TheFrontEnd:GetSound():PlaySound("dontstarve/HUD/click_negative", nil, .4)
                end
                return
            end
        -------------------------------------------------------------------------------------
        --- 技能释放
            if CanCastSpell(inst) then
                inst.replica.hutao_com_rpc_event:PushEvent("hutao_event.spell.BUTTERFLY_S_EMBRACE.start")
                ClientSideHotkeyCD(inst)
            else
                TheFrontEnd:GetSound():PlaySound("dontstarve/HUD/click_negative", nil, .4)
            end
        -------------------------------------------------------------------------------------
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

return function(inst)
    inst:ListenForEvent("hutao_hotkey_event.BUTTERFLY_S_EMBRACE",hotkey_press)
    if not TheWorld.ismastersim then
        return
    end
    inst:AddComponent("hutao_com_butterfly_s_embrace")
    inst.components.hutao_com_butterfly_s_embrace:SetStartFn(Spell_Fn)
    inst:ListenForEvent("hutao_event.spell.BUTTERFLY_S_EMBRACE.start",Spell_Start_Fn)
    inst:ListenForEvent("hutao_event.spell.BUTTERFLY_S_EMBRACE.stop",Spell_Stop_Fn)

end